<template>
  <el-dialog :append-to-body="true" :visible.sync="flowSendDialog" width="40%" :before-close="cancel" title="流程发送"
             @open="open">
    <el-form ref="form" size="small" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="下一步骤：" prop="selectNextStep">
            <el-select v-model="selectNextStep" value-key="nextStep" placeholder="请选择" @change="selectStep">
              <el-option
                v-for="(item,index) in nextStepList"
                :key="index"
                :label="item.nextStep"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="userShow" label="接收人：" prop="nextTodoName" v-show="!end">
            <el-input :value="nextTodoName.join('、')"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button icon="el-icon-user" v-if="show" @click="selectUser">选择</el-button>
        </el-col>
      </el-row>
      <el-form-item label="审批意见：">
        <el-col :span="24">
          <el-input v-model="opinion" :rows="10" type="textarea"/>
        </el-col>
      </el-form-item>
    </el-form>
    <user-select ref="DeptUserInfo" :dept-id="deptId" :role-flag="roleFlag" :mul-check="mulCheck" :is-expert="isExpert" @flowUser="flowUser"/>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="flowLoading" :disabled="send" type="primary" @click="flowSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getNextStepInfo, finishTask } from '@/api/business/flow/send'
  import UserSelect from '@/components/UserSelect'
  import { excVerify } from '@/api/business/flow/review'
  import { reviewTodoCount } from '@/utils/global'
  import { mapGetters } from 'vuex'
  import store from '../../store'

  export default {
    name: 'FlowSend',
    components: { UserSelect },
    props: {
      hzId: {
        type: String,
        required: true
      },
      proTaskList: {
        type: Array,
        required: true
      }
    },
    computed: {
      ...mapGetters([
        'user'
      ])
    },
    data() {
      return {
        nextTodoName: [],
        nextStepList: [],//下一步骤model
        mulUser: [],//多选人列表
        singleUser: '',//候选人
        selectFlag: false,//选择人标记
        mulCheck: 0,//是否多选
        isExpert:0,//是否选自专家库
        selectNextStep: {},
        flowSendDialog: false,
        flowLoading: false,
        show: false,//可选择人按钮
        userShow: true,//显示待办人信息
        opinion: '',//意见
        deptId: '0',//选择部门
        roleFlag: '',//部门中的角色
        send: true,//可以发送标记
        end: false//结束
      }
    },
    methods: {
      open() {
        getNextStepInfo(this.proTaskList).then(data => {
          this.nextStepList = data
          this.setDefaultStep(data)
        }).catch(error => {
          console.error(error)
        })
      },
      setDefaultStep(data) {
        data.forEach(item => {
          if (item.defaultStep) {
            this.selectNextStep = item
            this.selectStep(item)
          }
        })
      },
      cancel() {
        this.nextTodoName = []
        this.nextStepList = []//下一步骤model
        this.mulUser = []//多选人列表
        this.singleUser = ''//候选人
        this.selectFlag = false//选择人标记
        this.mulCheck = 0//是否多选
        this.isExpert=0
        this.selectNextStep = {}
        this.flowSendDialog = false
        this.flowLoading = false
        this.show = false//可选择人按钮
        this.userShow = true
        this.opinion = ''//意见
        this.deptId = '0'//选择部门
        this.roleFlag = ''//部门中的角色
        this.send = true//可以发送标记
        this.flowSendDialog = false
        this.end = false//结束
      },
      selectStep(step) {
        this.send = true
        this.selectFlag = false
        this.show = this.selectNextStep.show
        this.userShow = this.selectNextStep.userShow
        if (this.show) {
          //部门ID
          this.deptId = this.selectNextStep.defaultDeptId
          if (this.selectNextStep.defaultDeptId === 'candidate') {
            this.deptId = this.user.deptId
          }
          if (this.selectNextStep.defaultRole) {
            this.roleFlag = this.selectNextStep.defaultRole
          }
          this.mulCheck = this.selectNextStep.todoList
          this.isExpert= this.selectNextStep.isExpert
        }
        this.nextTodoName = step.name
        if ('结束' === step.nextStep) {
          this.end = true
        } else {
          this.end = false
        }
        this.verify(this.selectNextStep.verifyMethod)
      },
      flowSubmit() {
        if (!this.end) {
          if (Object.keys(this.nextStepList).length === 0) {
            this.$message({
              showClose: true,
              message: '请选择下一步骤',
              type: 'warning'
            })
            return
          }
          if (Object.keys(this.nextTodoName).length === 0 && this.userShow) {
            this.$message({
              showClose: true,
              message: '请选择待办人',
              type: 'warning'
            })
            return
          }
        }
        if (!this.userShow) {
          this.$confirm('此步骤满足条件的工程才能分发确定发送吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.sendFlow()
          })
        } else {
          this.sendFlow()
        }
      },
      sendFlow() {
        this.flowLoading = true
        const proTaskList = []
        this.proTaskList.forEach(item => {
            const proTask = {}
            const variables = {}
            proTask.procInstanceId = item.procInstanceId
            proTask.currentList = this.selectNextStep.currentList
            proTask.taskId = item.taskId
            proTask.key = sessionStorage.getItem('key')
            variables.opinion = this.opinion
            variables.taskDefKey = sessionStorage.getItem('taskDefKey')
            if (this.selectNextStep.defaultVar) {
              //流转变量必须设置为数字
              variables[this.selectNextStep.defaultVar] = this.selectNextStep.defaultVal
            }
            //多人办理？
            if (this.selectNextStep.todoList) {
              if (this.selectFlag) {
                //多人办理、并且选择了用户
                variables[this.selectNextStep.todoPersonVar] = this.mulUser
              } else {
                //多人办理、没有选择用户
                variables[this.selectNextStep.todoPersonVar] = this.selectNextStep.username
              }
            } else {
              //默认人员
              if (this.singleUser) {
                variables[this.selectNextStep.todoPersonVar] = this.singleUser
              } else {
                variables[this.selectNextStep.todoPersonVar] = this.selectNextStep.username.join('')
              }
            }
            variables.nextStep = this.selectNextStep.nextStep
            proTask.variables = variables
            proTaskList.push(proTask)
          }
        )
        finishTask(proTaskList).then(data => {
          this.flowLoading = false
          this.flowSendDialog = false
          try {
            this.$parent.init()
          } catch (e) {
          }
          this.findTodoCount() //重新查询待办数量
          this.cancel()
          this.$notify({
            title: '流程发送成功',
            type: 'success',
            duration: 1500
          })
        }).catch(err => {
          this.flowLoading = false
          console.log(err)
        })
      },
      selectUser() {
        this.$refs.DeptUserInfo.dialog = true
      }
      ,
      findTodoCount() {
        reviewTodoCount().then(number => {
          store.dispatch('Todo', number)
        })
      }
      ,
      verify(verifyMethod) {
        const params = {}
        if (verifyMethod) {
          params.hzId = this.hzId
          params.classLoad = verifyMethod
          params.taskDefKey=sessionStorage.getItem('taskDefKey')
          params.proParamList = this.proTaskList
          excVerify(params).then(res => {
            if (res.code) {
              this.$message({
                showClose: true,
                message: res.msg,
                type: 'warning'
              })
              this.send = true
            } else {
              this.send = false
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.send = false
        }
      }
      ,
      flowUser(selectUser) {
        this.mulUser = []
        this.selectFlag = false
        this.singleUser = ''
        this.nextTodoName = []
        selectUser.forEach(item => {
          this.nextTodoName.push(item.name)
          this.mulUser.push(item.username)
          this.singleUser = item.username
          this.selectFlag = true
        })
      }
    }
  }
</script>

<style scoped>

</style>
